//
//  HBPictureBrowserCell.swift
//  sinaWeibo
//
//  Created by Beans on 16/7/7.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit
import SDWebImage

class HBPictureBrowserCell: UICollectionViewCell {

    var tapToDismissClosure: (()->())?
    var longPressToSavePicClosure: (()->())?

    var viewModel: HBStatusPicViewModel? {
        didSet {
            // 1. 通过SDWebImage获取缩略图
            guard let thumbnailURLString = viewModel?.model?.thumbnail_pic else {
                return
            }
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(thumbnailURLString)
            thumbnailPicView.image = image
            thumbnailPicView.hidden = false

            // 2. 替换缩略图url并加载大图
            pictureView.sd_setImageWithURL(changeThunbnailToBmiddleURL(thumbnailURLString), placeholderImage: nil, options: [], progress: { (current, total) -> Void in
                // 注意: UI操作在主线程
//                printLog(NSThread.currentThread())

                let progress: CGFloat = CGFloat(current) / CGFloat(total)
                self.circleProgressView.progress = progress

                }) { (bmiddleImage, error, _, _) -> Void in
                    printLog("图片下载完成的回调")
                    // 显示大图并隐藏缩略图
                    self.showBmiddleImageView(bmiddleImage)
                    self.thumbnailPicView.hidden = true
            }
        }
    }

    private func changeThunbnailToBmiddleURL(thumbnailStr: String) -> NSURL {
        // 替换成中等图片url
        // http://ww1.sinaimg.cn/thumbnail/470bf257gw1f5l5jnbsr3j20dw0ijt9p.jpg
        let bmiddleURLString = (thumbnailStr as NSString).stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")

        return NSURL(string: bmiddleURLString)!
    }

    private func showBmiddleImageView(image: UIImage) {
        let imgW = kScreenWidth
        let imgH = imgW / image.size.width * image.size.height

        // 设置scrollView的contentSize
        pictureView.frame.size = CGSizeMake(imgW, imgH)
        scrollView.contentSize = pictureView.bounds.size

        // 如果图片的高度小于屏幕的宽度, 应该让图片居中
        if imgH < kScreenHeight {
//            let y = (kScreenHeight - imgH) * 0.5
////            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)    // 第二次点击同一张图片顶部移除屏幕外
//            scrollView.contentOffset = CGPointMake(0, -y)     // 第二次点击同一张图片是不再居中
            pictureView.center = contentView.center // 为什么这样就可以呢??
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
//        backgroundColor = color_HSB_Random()

        contentView.addSubview(thumbnailPicView)
        contentView.addSubview(circleProgressView)
        contentView.addSubview(scrollView)
        scrollView.addSubview(pictureView)
        scrollView.bounces = false

        thumbnailPicView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(contentView)
        }
        circleProgressView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(contentView)
            make.width.height.equalTo(100)
        }
        scrollView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
//        pictureView.snp_makeConstraints { (make) -> Void in
//            make.edges.equalTo(scrollView)     // 填充不满时再单独调; 不要设为center, 否则长图片从中间开始; 都不设置, 避免影响contentSize
//        }

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapAction:")
        addGestureRecognizer(tap)

        let longPress: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressAction:")
        longPress.minimumPressDuration = 2.0
        addGestureRecognizer(longPress)
    }

    @objc private func tapAction(recognizer: UIGestureRecognizer) {
        printLog("tap, dismiss")
        tapToDismissClosure?()
    }

    @objc private func longPressAction(recognizer: UIGestureRecognizer) {
        // MARK: - 通过手势识别器的状态信息,保证长按只执行一次
        if recognizer.state == UIGestureRecognizerState.Began {
            printLog("long press, save pic")
            saveImage()
        }
    }

    private func saveImage() {
        guard let image = pictureView.image else {
            return
        }
        // 保存到相册 (注意: 方法名为"image:didFinishSavingWithError:contextInfo:")
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }

    // MARK: - 系统提供的, 在图片保存完毕后会调用的方法
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    @objc private func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) {
        if didFinishSavingWithError == nil {
            longPressToSavePicClosure?()
        } else {
            printLog(didFinishSavingWithError)
        }
    }

    // MARK: - lazy load
    private lazy var thumbnailPicView: UIImageView = UIImageView()

    private lazy var scrollView: UIScrollView = UIScrollView()

    private lazy var pictureView: UIImageView = UIImageView()

    private lazy var circleProgressView: HBProgressCircleView = HBProgressCircleView()
}
